const express = require("express");
const cors = require("cors");
const mysql = require("mysql");
const bodyParser = require('body-parser')
const app = express();

app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

const conn = mysql.createConnection({
	host: "172.66.1.108", 
    // host: "localhost",
	user: "root", 
    port: 3306,
	password: "xlstl12345",
    database: "xlstldb",
    multipleStatements: true
});

conn.connect((error) =>{
    if (error) {
        console.error('连接失败：', error);
    } else {
        console.log('成功连接到数据库');
    }
});

app.get("/password", (req, res) => {
	conn.query("SELECT * FROM xlstldb.password",(error, result) => {
		if (error) throw error;
		res.send({
			message: "success",
			status: 200,
			data: result,
		});
	});
});

//查找PhoneNumber
app.post("/infoSearch", (req, res) => {
    conn.query(`SELECT * FROM xlstldb.project WHERE PhoneNumber = ${req.body.phoneNum}`,(error, result) => {
        if (error) throw error;
        res.send({
            message: "success",
            status: 200,
            data: result,
        });
    })
});

//更改PhoneNumber的mysql
app.post("/infoChange", (req, res) => {
    for (let i = 0; i < req.body.project.length; i++) {
        conn.query(`UPDATE xlstldb.project SET ${req.body.project[i].name} = ${req.body.project[i].num} WHERE PhoneNumber = ${req.body.phoneNum}`,(error, result) => {
            if (error) throw error;
        })
    }
    res.send({
        message: "success",
        status: 200,
    });
});

//向project表中插入数据
app.post("/CreateUser", (req, res) => {
    conn.query(`INSERT INTO xlstldb.project (PhoneNumber) VALUES (${req.body.phoneNum})`,(error, result) => {
        if (error) throw error;
        res.send({
            message: "success",
            status: 200,
            data: result,
        });
    })
});

app.listen(9000, () => {
	console.log("success in 9000");
});
